package com.oazon.moco.lan.core.http;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

import java.util.List;

public class HttpJsonResponseEncoder extends AbsHttpJsonEncoder<HttpJsonResponse> {

	@Override
	protected void encode(ChannelHandlerContext ctx, HttpJsonResponse message,
			List<Object> out) throws Exception {
		ByteBuf body = encode(ctx, message.getResult());
		FullHttpResponse response = message.getHttpResponse();
		if(response == null){
			response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,body);
		}else{
			response = new DefaultFullHttpResponse(message.getHttpResponse().getProtocolVersion(), 
					message.getHttpResponse().getStatus(),body);
		}
		response.headers().set(HttpHeaders.Names.CONTENT_TYPE,"text/html;charset=UTF-8");
		HttpHeaders.setContentLength(response, body.readableBytes());
		out.add(response);
	}

}
